<template>
  <div>
    <el-card shadow='never'>
      <div slot="header">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }"><i class="el-icon-house"></i>首页</el-breadcrumb-item>
          <el-breadcrumb-item>活动管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 表格区域 -->
      <div class="filter-form">
        <el-input v-model="params.query"
                  size="small"
                  clearable
                  @clear='getUserList'
                  class="ipt">
          <template slot="append"><i @click='getUserList'
               class="el-icon-search"></i></template>
        </el-input>
        <el-button @click='openshow'
                   type="primary"
                   size="small"
                   icon="el-icon-plus">增加</el-button>
      </div>
      <!-- 表格 -->
      <el-table :data="list"
                border>
        <el-table-column label="序号"
                         width="100"
                         type='index'>
        </el-table-column>
        <el-table-column label="用户名"
                         prop="username">
        </el-table-column>
        <el-table-column label="邮箱"
                         prop="email">
        </el-table-column>
        <el-table-column label="手机号"
                         prop="mobile">
        </el-table-column>
        <el-table-column label="状态"
                         align='center'>
          <template slot-scope='scope'>
            <el-switch v-model="scope.row.mg_state"
                       @change='changeStatus(scope.row.id,$event)'
                       active-color="#13ce66"
                       inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template slot-scope="scope">
            {{scope.row.create_time | formate('YYYY/MM/DD')}}
          </template>
        </el-table-column>
        <el-table-column label="角色名称"
                         prop="role_name">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click='edit(scope.row)'
                       size='small'
                       type='success'
                       icon='el-icon-edit'
                       circle></el-button>
            <el-button @click='del(scope.row)'
                       size='small'
                       type='danger'
                       icon='el-icon-delete'
                       circle></el-button>
            <el-button size='small'
                       @click='auth(scope.row)'
                       type='warning'
                       icon='el-icon-setting'
                       circle></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <!-- page-size属性表示 每页个数 -->
      <!-- total属性表示 总条数 -->
      <!-- current-page属性表示 当前页码数 -->
      <el-pagination background
                     @size-change='sizeChange'
                     @current-change='currentChange'
                     :page-size='params.pagesize'
                     :current-page='params.pagenum'
                     layout="sizes,prev, pager, next,->,total"
                     :page-sizes='[1,2,3,4]'
                     :total="total">
      </el-pagination>
      <!--增加弹框 -->
      <el-dialog title="添加用户"
                 width="50%"
                 :visible.sync="isAddshow">
        <el-form ref="addFormInfo"
                 size='normal'
                 :rules='addFormRules'
                 :inline='false'
                 :model='addFormInfo'>
          <el-form-item label="用户"
                        prop='username'>
            <el-input style="width:90%"
                      v-model='addFormInfo.username'></el-input>
          </el-form-item>
          <el-form-item label="密码"
                        prop='password'>
            <el-input style="width:90%"
                      v-model='addFormInfo.password'></el-input>
          </el-form-item>
          <el-form-item label="邮箱"
                        prop='email'>
            <el-input style="width:90%"
                      v-model='addFormInfo.email'></el-input>
          </el-form-item>
          <el-form-item label="手机"
                        prop='mobile'>
            <el-input style="width:90%"
                      v-model='addFormInfo.mobile'></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer"
             class="dialog-footer">
          <el-button @click='isAddshow=false'>取 消</el-button>
          <el-button @click='editSubmit'
                     type='primary'>确 定</el-button>
        </div>
      </el-dialog>
      <!-- 修改弹框 -->
      <el-dialog title="修改"
                 width="50%"
                 :visible.sync="isEditShow">
        <el-form ref="editFormInfo"
                 size='normal'
                 :rules='editFormRules'
                 :inline='false'
                 :model='editFormInfo'>

          <el-form-item label="邮箱"
                        prop='email'>
            <el-input style="width:90%"
                      v-model='editFormInfo.email'></el-input>
          </el-form-item>
          <el-form-item label="手机"
                        prop='mobile'>
            <el-input style="width:90%"
                      v-model='editFormInfo.mobile'></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer"
             class="dialog-footer">
          <el-button @click='isEditShow=false'>取 消</el-button>
          <el-button @click='editSubmit'
                     type='primary'>确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="用户授权角色"
                 :visible.sync="isAuthShow"
                 width="30%">
        <span>
          <p>用户昵称：{{authUserInfo.username}}</p>
          <p>用户角色：{{authUserInfo.role_name}}</p>
          <p>授权角色：
            <el-select v-model='rid'>
              <el-option v-for="item in rolelist"
                         :key="item.id"
                         :label="item.roleName"
                         :value="item.id">
              </el-option>
            </el-select>

          </p>
        </span>
        <span slot="footer">
          <el-button @click="isAuthShow= false">Cancel</el-button>
          <el-button type="primary"
                     @click="userAuthSubmit">OK</el-button>
        </span>
      </el-dialog>

    </el-card>

  </div>
</template>

<script>
const checkMobile = (rule, value, callback) => {
  const reg = /^1[3|4|5|6|7|8|9]\d{9}$/
  if (reg.test(value)) {
    callback()
  } else {
    callback(new Error('手机格式不正确'))
  }
}
export default {
  name: 'User',
  data() {
    return {
      list: [], //列表数据
      params: {
        query: '', //查询参数
        pagenum: 1, //页码
        pagesize: 1 //每页数量
      },
      total: 0,
      isAddshow: false, //增加弹框控制
      addFormInfo: {
        //添加表单
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '用户名不为空', trigger: 'blur' }
        ],
        password: [{ required: true, message: '密码不为空', trigger: 'blur' }],
        email: [{ type: 'email', message: '邮箱不为空', trigger: 'blur' }],
        mobile: [{ validator: checkMobile, trigger: 'blur' }]
      },
      isEditShow: false,
      editFormInfo: {
        email: '11@qq.con',
        mobile: '13312346578'
      },
      editFormRules: {
        email: [{ type: 'email', message: '邮箱格式不真确', trigger: 'blur' }],
        mobile: [{ validator: checkMobile, trigger: 'blur' }]
      },
      isAuthShow: false,
      authUserInfo: {},
      rolelist: [],
      rid: ''
    }
  },
  created() {
    this.getUserList()
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$axios.get('/roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolelist = res.data
    },
    openshow() {
      console.log(1111)
      this.isAddshow = true
    },
    //获取用户列表
    async getUserList() {
      // 1.请求
      const { data: res } = await this.$axios.get('/users', {
        params: this.params
      })
      //2.失败处理
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      //3.成功处理
      this.total = res.data.total
      this.list = res.data.users
    },
    async changeStatus(uid, state) {
      const { data: res } = await this.$axios.put(
        `/users/${uid}/state/${state}`
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('修改状态成功')
    },
    //页码变化
    currentChange(val) {
      //val是最新页码
      this.params.pagenum = val
      this.getUserList()
    },
    //每页数量变化
    sizeChange(val) {
      //是最新的没页数量
      this.params.pagesize = val
      this.getUserList()
    },
    //添加提交
    addSubmit() {
      // 验证
      this.$refs.addFormInfo.validate(async valid => {
        //不通过跳出
        if (!valid) return
        //跳出
        const { data: res } = await this.$axios.post('/users', this.addFormInfo)
        //失败chu处理
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        //成功处理，提示弹框，拉列表， 关闭对话框
        this.$message.success('增加成功')
        this.getUserList()
        this.isAddshow = false
      })
    },
    editSubmit() {
      this.$refs.editFormInfo.validate(async valid => {
        if (!valid) return false
        const id = this.editFormInfo.id
        const { data: res } = await this.$axios.put(
          `/users/${this.editFormInfo.id}`,
          this.editFormInfo
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('修改成功')
        this.getUserList()
        this.isEditShow = false
      })
    },
    edit(val) {
      this.isEditShow = true
      this.editFormInfo = val
    },
    async del(val) {
      try {
        await this.$confirm(`确定删除${val.username}吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const { data: res } = await this.$axios.delete('/users/' + val.msg)
        this.$message.success('删除成功')
        if (this.params.pagenum !== 1 && this.list.length === 1) {
          this.params.pagenim--
        }
        this.getUserList()
      } catch (error) {
        console.log(error)
        this.$message.info('取消删除')
      }
    },
    auth(val) {
      this.authUserInfo = val
      this.isAuthShow = true
    },
    async userAuthSubmit() {
      const { data: res } = await this.$axios.put(
        `/users/${this.authUserInfo.id}/role`,
        {
          rid: this.rid
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.authUserInfo = {}
      this.rid = ''
      this.isAuthShow = false
      this.getUserList()
    }
  }
}
</script>

<style>
</style>